
**** Table 3 Panel C: OOS results (and its t values) for Multi-Period Returns
 
clear

use mydata

rename *, lower

eststo clear

global ssize = _N

gen dm=mofd(date)
format dm %tm
tsset dm

* Taking lags of variables

gen l1mktrf = l1.mktrf
gen l1amihud =l1.amihud
gen l1tover = l1.tover
gen l1hml = l1.hml
gen l1smb = l1.smb
gen lsyy = l1.syy

local num =1


*** cumulative returns of SYY up to 12 month **
gen R =0

forvalues f=0/11 {
local g = `f'+1
gen syy_1`g' = (1+R)*(1+f`f'.syy)-1 // generating holding period returns ***
replace R = syy_1`g'
}

local train 120 // training period. 

save oss_temp, replace

matrix OOS_T=J(3,6,.) // output dimension ....

local x = 1


foreach flowvar in hfflow_ma active_ma {

foreach f in 0 2 5 {

gen xvar = l1.`flowvar'

local g = `f'+1	// holding period
local ctrlvar lsyy l1mktrf l1amihud l1tover l1hml l1smb // control variables 

matrix OOS_T[1,`x']=`g' 

local period `train'  
scalar define k = $ssize - `period' - `f' 
local y=k //the periods left for forcasting

gen yhat_a = .  // yhat of alternative model. The fittted value from the training model using x var (flow in this case)
gen yhat_n = .  // yhat of null model. Historical average of y var in this case

forvalues i=1/`y' {

qui reg xvar `ctrlvar' if _n<= `period' +`i' +`f' // model to obtain residual flow for recursive OSS
qui predict res_flow if  _n<= `period' +`i' +`f', re  // residual flows is the regressor in the training model  

qui reg syy_1`g' res_flow if _n< `period' +`i'  // training model for recursive OOS prediction: anomalies on residual flows
qui replace yhat_a=_b[_cons] + _b[res_flow]*res_flow  if _n== `period' +`i' +`f' // fitted value using the trained model  

qui su syy_1`g' if _n< `period' +`i'
qui replace yhat_n=r(mean) if _n== `period' +`i' +`f' // yhat of null model. Historical average
drop res_flow
}

*Sqaure of Prediction error (SE)
gen se_a = (syy_1`g' - yhat_a)^2
gen se_n = (syy_1`g' - yhat_n)^2

su se_a 
scalar define MSE_A = r(mean)
su se_n 
scalar define MSE_N = r(mean)


// OSS R2
dis "******************Training Period is `train'*******************************"
dis "OSS-R2:  " (1 - MSE_A/MSE_N) 
dis "***************************************************************************"
matrix OOS_T[2,`x']= (1 - MSE_A/MSE_N)*100


*** Clark and Weset (2007) t-test with bootstrap
gen CW = se_n - se_a + (yhat_n - yhat_a)^2

qui reg CW , vce(bootstrap, rep(1000))
scalar define t_CW = _b[_cons]/_se[_cons]
matrix OOS_T[3,`x']= t_CW

local ++x
use oss_temp, clear
}

}

** saving the OOS results 

mat rownames OOS_T = Period OOS-R2(%) OOS-T_CWbs
matrix list OOS_T, format(%9.3f)

putexcel set T3C, sheet(PanelC) modify
putexcel A1=matrix(OOS_T), names


